//
//  XGViewController.swift
//  WeIBo
//
//  Created by 苏文潇 on 2017/3/5.
//  Copyright © 2017年 苏文潇. All rights reserved.
//

import UIKit

class XGViewController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        添加边缘手势代理
        self.interactivePopGestureRecognizer?.delegate = self
    }
    
    //  重写push方法,监听push操作
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
//        print(viewControllers.count)
        //        如果viewControllers.count > 0 就需要隐藏
        if viewControllers.count > 0
        {
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: animated)
        
        if viewControllers.count > 1
        {
            if viewControllers.count == 2
            {
      //  获取导航栏里面的第一个子视图控制器的标题
//   这里会出现一个大问题，就是在tabBarController中设置title的时候如果是分别设置的话在这里重写push这个方法中的viewControllers.first!.title!这里就拿不到title，值为nil，只要是统一设置的title才可以拿到title的值
                let title = viewControllers.first!.title!
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, imageName: "navigationbar_back_withtext", target: self, action: #selector(popAction))
            }
            else
            {
                //  统一标题改成返回
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(popAction))
            }
            viewController.title = "当前显示的是第\(viewControllers.count)级控制器"
        }
    }
    
    
    @objc private func popAction() {
        
        self.popViewController(animated: true)
        
    }
  
}

extension XGViewController: UIGestureRecognizerDelegate {
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
    {
//        如果是跟视图，就不让其执行这个边缘手势
        if viewControllers.count == 1 {
            return false
        }
        return true
    }
    
}
